<?php
// {{{ class Logger
/**
 * Logger
 * 動作ログ管理
 * 
 * @author		risukan@hotmaill.com
 * @license		-
 * @version		0.01
 * @link		http://bouyke.com/
 */

class Logger {
	private $DebugLog;
	private $StartTime;
	private $PastTime;
	private $Time;
	private $Memory;
	private $Memory_peak;
	
	function __construct () {
		$this->DebugLog = array(array('trace'=>'Logger', 'txt'=>'デバッグログ取得開始', 'time'=>0, 'past'=>0));
		$this->StartTime = microtime(true);
		$this->PastTime = 0;
		return;
	}

	public function init () {
		Y('this.Output+' , 'javascript');

		Y('this.Debug+' , YuTori::create($this, 'setDebug'));
		Y('this.getDebug+' , YuTori::create($this, 'getDebug'));
		Y('this.getTime+' , YuTori::create($this, 'getTime'));
		Y('this.getMemory+' , YuTori::create($this, 'getMemory'));
		Y('this.getMemoryPeak+' , YuTori::create($this, 'getMemoryPeak'));
//		Y('this.objTree+' , YuTori::loadSystem('logger/objtree'));
		return true;
	}

	/**
	 * デバッグログの追加
	 */	
	function setDebug ($Log) {
		// トレースログの作成
		$tLog = Y()->objNameByID(Y()->nowselCursor(1), true);
		// 長すぎるログは省略する
		$Txt = null;
		foreach ((array)$Log as $val) {
			$Txt .= mb_strimwidth($val, 0, 1024, '...'). "\n";
		}
		$Time = microtime(true) - $this->StartTime;
		$this->PastTime = $Time - $this->PastTime;
		$this->DebugLog[] = array(
			'trace'=>$tLog,
			'txt'=>$Txt,
			'time'=> $Time,
			'past'=>$this->PastTime
		);
		return true;
	}

	/**
	 * デバッグログの取得
	 */
	public function getDebug () {
		return $this->DebugLog;
	}

	/**
	 * 処理時間の取得
	 */
	public function getTime () {
		return microtime(true) - $this->StartTime;
	}

	/**
	 * メモリ使用量の取得
	 */
	public function getMemory () {
		return number_format(memory_get_usage(true));
	}

	/**
	 * メモリ使用量(peak)の取得
	 */
	public function getMemoryPeak () {
		return number_format(memory_get_peak_usage(true));
	}

	/**
	 * オブジェクトツリー表示
	 */
	public function objTree () {
		if (Y('Logger.Debug$')) Y('Logger.Debug', 'objTree 開始');
		$this->Tree = 0;
		$Tree = '<ul><li>'.Y()->objNameByID(0).'</li>';
		$Tree .= $this->rec_output(0);
		$Tree .= '</li></ul>';
		return $Tree;
	}
	
	private function rec_output ($ID) {
		$Children = Y()->children($ID);
		$Tree = '<ul>';
		if ($Children) {
			foreach ($Children as $Child) {
				$Tree .= '<li>['.$Child.'] '.Y()->objNameByID($Child).' : '.$this->getValue(Y()->get($Child));
				$Tree .= $this->rec_output($Child);
				$Tree .= '</li>';
			}
		}

		$Tree .= '</ul>';
		return $Tree;
	}
	
	private function getValue ($Var) {
		if (is_object ($Var)) {
			return get_class($Var);
		} elseif (is_bool($Var)) {
			return ($Var)?('(bool)true'):('(bool)false');
		} elseif (is_null($Var)) {
			return '(null)';
		} else {
			return $Var;
		}
	}

}
// }}}
?>